package cc.linker.steplink.crm.merchanth5.service.tl;

import cc.linker.steplink.crm.commons.FeeConstants;
import cc.linker.steplink.crm.commons.constant.TlPayConstant;
import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.pojo.acs.AccountInfo;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cc.linker.steplink.crm.merchanth5.service.impl.PurchaseProcessServiceImpl.ACS_CREATE_ORDER_INFO;
import static cc.linker.steplink.crm.merchanth5.service.impl.PurchaseProcessServiceImpl.ACS_CREATE_ORDER_RESULT;

@Slf4j
@Service
public class LedgerProcessService {
    @Autowired
    private MallBoomDao mallBoomDao;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Lazy
    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private WcPayProperties wcPayProperties;
    @Autowired
    private HttpService httpService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private SystemProperties systemProperties;


    /**
     * 通联退款（全额）
     *
     * @return 退款状态：10进行中；30成功；40失败
     */
    public Map<String, Object> refundAll(String orderSn) {
        // 全额退款
        String url = wcPayProperties.getAcsurl() + TlPayConstant.TRADE_REFUND;
        Map<String, Object> orderInfo = purchaseProcessDao.getOrderInfoByOrderSn(orderSn);
        if (orderInfo == null) {
            throw GlobalException.build("订单信息不存在");
        }
        String orgId = (String) orderInfo.get("orgId");
        String customerId = (String) orderInfo.get("customerId");
        if (StringUtils.isEmpty(customerId)) {
            throw GlobalException.build("用户信息获取失败");
        }
        Map<String, Object> req = new HashMap<>();
        // orderSn	    steplink平台对应订单ID	string
        req.put("orderSn", orderSn);
        // customerId	退款用户ID	            string
        req.put("customerId", customerId);
        String notifyUrl = systemProperties.getScrmUrl() + "acs/refundcallback";
        req.put("notifyUrl", notifyUrl);
        // refundOrderSn        退款id
        String refundOrderSn = TransactionOrderUtil.TYPE_REFUND + TransactionOrderUtil.getPrimaryKey();
        req.put("refundOrderSn", refundOrderSn);
        // clintType	        应用别名，测试使用yt	    string
        String alias = maiBaoLaService.getAlias(orgId);
        req.put("clintType", alias);
        String result = this.callTlAndReturn(url, req);
        Map<String, Object> map = new HashMap<>();
        map.put("result", result);
        map.put("refundOrderSn", refundOrderSn);
        return map;
    }

    /**
     * 通联提现转账退款
     *
     * @return 退款状态：10进行中；30成功；40失败
     */
    public Map<String, Object> refundTransferAmount(String orgId,String customerId,String orderSn,String alias) {
        // 全额退款
        String url = wcPayProperties.getAcsurl() + TlPayConstant.TRADE_REFUND;
        Map<String, Object> req = new HashMap<>();
        // orderSn	    steplink平台对应订单ID	string
        req.put("orderSn", orderSn);
        // customerId	退款用户ID	            string
        req.put("customerId", customerId);
        String notifyUrl = systemProperties.getScrmUrl() + "acs/transferRefundCallBack";
        req.put("notifyUrl", notifyUrl);
        // refundOrderSn        退款id
        String refundOrderSn = TransactionOrderUtil.TYPE_REFUND + TransactionOrderUtil.getPrimaryKey();
        req.put("refundOrderSn", refundOrderSn);
        // clintType	        应用别名，测试使用yt	    string
        req.put("clintType", alias);
        String result = this.callTlAndReturn(url, req);
        Map<String, Object> map = new HashMap<>();
        map.put("result", result);
        map.put("refundOrderSn", refundOrderSn);
        return map;
    }


    /**
     * 通联退款（部分）
     */
    public Map<String, Object> refund(String orderSn, String balanceAmount, String balanceSplitItems, String cashAmount, String cashSplitItems,String  paySn,Integer payMode) {
        // 部分退款
        String url = wcPayProperties.getAcsurl() + TlPayConstant.TRADE_PAY_ORDER_REFUND;
        Map<String, Object> orderInfo = purchaseProcessDao.getOrderInfoByOrderSn(orderSn);
        if (orderInfo == null) {
            throw GlobalException.build("订单信息不存在");
        }
        String customerId = (String) orderInfo.get("customerId");
        if (StringUtils.isEmpty(customerId)) {
            throw GlobalException.build("用户信息获取失败");
        }

        String orgId = (String) orderInfo.get("orgId");
        String alias = "";
        if(payMode == 3){
            alias = maiBaoLaService.getAliasByLinker();
        }
        if(payMode == 2){
            alias = maiBaoLaService.getAlias(orgId);
        }
//        alias = "yt";
        String notifyUrl = systemProperties.getScrmUrl() + "acs/refundcallback";
        Map<String, Object> req = new HashMap<>();
        // balanceAmount	    金币退款总金额	        string
        req.put("balanceAmount", balanceAmount);
        // balanceSplitItems	金币退款明细	            string
        // @mock=[{"bizUserId":"LINKERbTEEfjPreu","amount":"2"}]
        req.put("balanceSplitItems", balanceSplitItems);
        // cashAmount	        现金退款总金额	        string
        req.put("cashAmount", cashAmount);
        // cashSplitItems	    现金退款明细	            string
        req.put("cashSplitItems", cashSplitItems);
        // clintType	        应用别名，测试使用yt	    string
        req.put("clintType", alias);
        // notifyUrl	        回调通知地址	            string
        req.put("notifyUrl", notifyUrl);
        // orderSn	            steplink系统退款订单ID	string
        req.put("orderSn", paySn);
        // refundOrderSn        退款id
        String refundOrderSn = TransactionOrderUtil.TYPE_REFUND + TransactionOrderUtil.getPrimaryKey();
        req.put("refundOrderSn", refundOrderSn);
        String result = this.callTlAndReturn(url, req);
        Map<String, Object> map = new HashMap<>();
        map.put("result", result);
        map.put("refundOrderSn", refundOrderSn);
        return map;
    }

    /**
     * 请求通联退款接口并返回结果
     */
    public String callTlAndReturn(String url, Map<String, Object> req) {
        String result;
        try {
            LOGGER.info("callTlAndReturn,request===[{}]", JSON.toJSONString(req));
            result = httpService.doPost(url, JSON.toJSONString(req), WcPayConstant.JSON);
        } catch (URISyntaxException | IOException e) {
            throw GlobalException.build("通联网关调用异常");
        }
        LOGGER.info("callTlAndReturn,result===[{}]", result);
        Map parse = (Map) JSON.parse(result);
        if (!"200".equals(parse.get("code"))) {
            throw GlobalException.build("退款失败，" + (parse.get("msg") == null ? "" : parse.get("msg")));
        }
        Map data = (Map) parse.get("data");
        String status = (String) data.get("status");
        if (StringUtils.isEmpty(status) || "40".equals(status)) {
            throw GlobalException.build("退款失败");
        }
        return status;
    }
}
